<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.js"></script>
    <style>
        *{margin: 0;padding: 0;}
        .item>img{
            width: 300px;
        }
        #app{
            overflow: hidden;
        }
        .item{
            padding: 10px;
            border: 1px solid #777;
            float: left;
            font-size: 0;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="item"><img src="images/01.jpg" alt=""></div>
        <div class="item"><img src="images/02.jpg" alt=""></div>
        <div class="item"><img src="images/03.jpg" alt=""></div>
        <div class="item"><img src="images/04.jpg" alt=""></div>
        <div class="item"><img src="images/05.jpg" alt=""></div>
        <div class="item"><img src="images/06.jpg" alt=""></div>
        <div class="item"><img src="images/07.jpg" alt=""></div>
        <div class="item"><img src="images/08.jpg" alt=""></div>
        <div class="item"><img src="images/09.jpg" alt=""></div>
        <div class="item"><img src="images/10.jpg" alt=""></div>
        <div class="item"><img src="images/11.jpg" alt=""></div>
        <div class="item"><img src="images/12.jpg" alt=""></div>
    </div>

    <script>
        // 1.得到一排能放几个元素
        var ww = $(window).width();//内容的宽度,content
        var box = $(".item").outerWidth();//整个盒子的宽度，包括padding 和 border
        var num = Math.floor(ww/box);//一排能放几个
        // $("#app").css({width:num*box+"px"});

        // 2.定义一个数组获取第一排的height
        console.log($(".item"));
        var arr=[];
        //遍历
        $(".item").each((index,value)=>{
            // console.log(num);
            if(index<num){
                // console.log(value);
                var height = $(value).outerHeight();//获取最小的块的高度值
                // console.log(height);
                arr.push(height)
                // console.log('arr: ', arr);
            }else{
                var minHeight = Math.min(...arr);//获取数组中的最小值
                var index = arr.indexOf(minHeight);//通过最小值获取第一排最短的块的下标
                var offsetLeft = $(".item").eq(index).offset().left;//获取最短块的左边距
                $(value).css({position:"absolute",left:offsetLeft,top:minHeight});//给当前遍历的块设置左边距(和上边的相同)
                arr[index] = minHeight+$(value).outerHeight();//更新最短的块的值
            }
        })
    </script>
</body>
</html>